package com.hejiale.lease.web.admin.service.impl;

import com.hejiale.lease.common.constant.RedisConstant;
import com.hejiale.lease.common.exception.LeaseException;
import com.hejiale.lease.common.result.ResultCodeEnum;
import com.hejiale.lease.common.threadlocal.LoginThreadLocalHolder;
import com.hejiale.lease.common.utils.JwtUtil;
import com.hejiale.lease.model.entity.SystemUser;
import com.hejiale.lease.model.enums.BaseStatus;
import com.hejiale.lease.web.admin.mapper.SystemUserMapper;
import com.hejiale.lease.web.admin.service.LoginService;
import com.hejiale.lease.web.admin.service.SystemUserService;
import com.hejiale.lease.web.admin.vo.login.CaptchaVo;
import com.hejiale.lease.web.admin.vo.login.LoginVo;
import com.hejiale.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.wf.captcha.SpecCaptcha;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @description: 登录服务实现类
 * @author: HeJiale
 * @since 2025/3/20 下午5:03
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SystemUserMapper systemUserMapper;

    /**
     * 获取验证码
     * @return
     */
    @Override
    public CaptchaVo getCaptcha() {
        // 设置图片宽度、高度、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);

        // 获取验证码文本并转化为小写
        String verCode = specCaptcha.text().toLowerCase();

        // 生成一个全局唯一的随机字符串，作为验证码的唯一标识符(Key)
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString();

        // 将生成的验证码图片转换为 Base64 编码的字符串
        String img = specCaptcha.toBase64();

        // 存入redis并设置过期时间为30分钟
        redisTemplate.opsForValue().set(key, verCode, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.MINUTES);

        return new CaptchaVo(img, key);
    }

    /**
     * 登录校验
     * @param loginVo
     */
    @Override
    public String login(LoginVo loginVo) {
        String code = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        // 验证码是否过期
        if (code == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        // 未输入验证码
        if (loginVo.getCaptchaCode() == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }

        // 验证码比较
        if (!code.equals(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        // 用户不存在
        SystemUser systemUser = systemUserMapper.selectOneByUsername(loginVo.getUsername());
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        // 密码错误
        if (!(DigestUtils.md5Hex(loginVo.getPassword())).equals(systemUser.getPassword())){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        // 检测账号状态
        if(systemUser.getStatus() == BaseStatus.DISABLE ){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        // 销毁Redis中的验证码
        redisTemplate.delete(loginVo.getCaptchaKey());

        // 返回Token
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }

    /**
     * 从threadLocal中获取用户信息,并封装成VO返回
     * @return
     */
    @Override
    public SystemUserInfoVo getLoginUserInfo() {
        SystemUser systemUser = systemUserMapper.selectById(LoginThreadLocalHolder.getLoginUser().getUserId());
        return SystemUserInfoVo.builder()
                .name(systemUser.getName())
                .avatarUrl(systemUser.getAvatarUrl())
                .build();
    }
}
